<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Http\Models\OrderModel;
use App\Http\Models\UserModel;
use Overtrue\Wechat\Payment;
use Overtrue\Wechat\Payment\Order as Wxorder;
use Overtrue\Wechat\Payment\Business;
use Overtrue\Wechat\Payment\UnifiedOrder;
use DB;
use App\Http\Models\ExpressorderModel;
use App\Http\Models\ExpressModel;
use PHPExcel;

class OrderController extends Controller
{
    //首页展示
    public function index(Request $request)
    {
        if ($request->isMethod('get')) {
            $data['data'] = OrderModel::select('order.*', 'user.name', 'user.nikename', 'user.mobile')
                ->join('user', 'order.openid', '=', 'user.openid')
                ->paginate(10);
            $express = ExpressModel::get();
            $data['type'] = 3;
            return view('order.index', compact('data', 'express'));
        } else {

            $where = [
                'role' => $request->input('role'),
                'express_id' => $request->input('express_id'),
                'datemax' => $request->input('datemax'),
                'datemin' => $request->input('datemin')
            ];
            $where = $this->where_data($where);
            if (!empty($where)) {
                if (isset($where['datemax'])) {
                    $datemax = $where['datemax'];
                    $_datemax = $request->input('datemax');
                } else {
                    $_datemax = 0;
                }
                if (isset($where['datemin'])) {
                    $datemin = $where['datemin'];
                    $_datemin = $request->input('datemin');
                } else {
                    $_datemin = 0;
                }
                unset($where['datemax']);
                unset($where['datemin']);
                if (!empty($datemax) && !empty($datemin)) {
                    /*                    echo $datemax ;
                                        echo date('Y-m-d H:i:s',$datemax) ;
                                        echo '<hr>';
                                        echo $datemin ;
                                        echo date('Y-m-d H:i:s',$datemin) ;*/
                    $data['data'] = OrderModel::whereBetween('create_time', array($datemin, $datemax))
                        ->where($where)
                        ->paginate(10);
                    //dd( $data['data']);
                } elseif (!empty($datemin)) {

                    $data['data'] = OrderModel::where('create_time', '>', $datemin)
                        ->where($where)
                        ->paginate(10);
                } elseif (!empty($datemax)) {
                    $data['data'] = OrderModel::where('create_time', '<', $datemax)
                        ->where($where)
                        ->paginate(10);
                } else {
                    $data['data'] = OrderModel::where($where)
                        ->paginate(10);
                }

                if (!empty($data['data']))
                    foreach ($data['data'] as $key => $value) {
                        $user_info = UserModel::where('openid', $value['openid'])->first();
                        $data['data'][$key]['name'] = $user_info->name;
                        $data['data'][$key]['nikename'] = $user_info->nikename;
                        $data['data'][$key]['mobile'] = $user_info->mobile;
                    }
            } else {
                $data['data'] = OrderModel::select('order.*', 'user.name', 'user.nikename', 'user.mobile')
                    ->join('user', 'order.openid', '=', 'user.openid')
                    ->paginate(10);
            }


        }
        if ($request->input('status') == 1) {
            if (!empty($data['data'])) {
                $data = $data['data']->toArray();

                $this->save_excel($data['data']);
            }


        }
        $express = ExpressModel::get();
        $data['type'] = 3;
        return view('order.index', compact('data', 'express'));


    }


    public function save_excel($data)
    {

        foreach ($data as $k => $v) {
            if ($v['role'] == 1) {
                $data[$k]['role'] = '教师';
            } else {
                $data[$k]['role'] = '学生';
            }
            if ($v['status'] != 0) {
                $data[$k]['status'] = '已支付';
            } else {
                $data[$k]['status'] = '未支付';
            }
            $data[$k]['create_time'] = date('Y-m-d H:i:s', $v['create_time']);
        }

        header("Content-Type:text/html;charset=utf-8");
        error_reporting(E_ALL);
        ini_set('display_errors', TRUE);
        ini_set('display_startup_errors', TRUE);
        //创建对象
        $excel = new PHPExcel();
        $excel->getActiveSheet()->setTitle('取件下单订单');
        //Excel表格式,这里简略写了8列
        $letter = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S');
        //表头数组
        $tableheader = array('订单id', '用户标识', '状态', '微信支付号', '订单唯一编号', '价格', '创建时间', '取件码', '快递id', '快递名称', '运单号', '角色', '下单姓名', '用户昵称', '手机号');
        //填充表头信息
        for ($i = 0; $i < count($tableheader); $i++) {

            $excel->getActiveSheet()->setCellValue("$letter[$i]1", "$tableheader[$i]");
        }


        $data = json_decode(json_encode($data), true);

        //填充表格信息
        for ($i = 2; $i <= count($data) + 1; $i++) {
            $j = 0;
            foreach ($data[$i - 2] as $key => $value) {
                $excel->getActiveSheet()->setCellValue("$letter[$j]$i", "$value");
                $j++;
            }
        }

        //创建Excel输入对象
        ob_end_clean();
        $objWriter = new \PHPExcel_Writer_Excel5($excel);
        header("Pragma: public");
        header("Expires: 0");
        header("Cache-Control:must-revalidate, post-check=0, pre-check=0");
        header("Content-Type:application/force-download");
        header("Content-Type:application/vnd.ms-execl");
        header("Content-Type:application/octet-stream");
        header("Content-Type:application/download");
        //多浏览器下兼容中文标题
        $fileName = '取件下单人员' . date("Y-m-d-h-i-s", time());
        $encoded_filename = urlencode($fileName);
        $ua = $_SERVER["HTTP_USER_AGENT"];
        if (preg_match("/MSIE/", $ua)) {
            header('Content-Disposition: attachment; filename="' . $encoded_filename . '.xls"');
        } else if (preg_match("/Firefox/", $ua)) {
            header('Content-Disposition: attachment; filename*="utf8\'\'' . $fileName . '.xls"');
        } else {
            header('Content-Disposition: attachment; filename="' . $fileName . '.xls"');
        }
        header("Content-Transfer-Encoding:binary");
        $objWriter->save('php://output');

    }


    public function where_data($data)
    {
        foreach ($data as $k => $v) {
            if (empty($v)) {
                unset($data[$k]);
            }
        }
        if (isset($data['datemax']))
            $data['datemax'] = strtotime($data['datemax']) + 3600 * 24;
        if (isset($data['datemin']))
            $data['datemin'] = strtotime($data['datemin']);
        return $data;
    }


    public function del(Request $request)
    {
        $id = $request->input('id');
        $res = OrderModel::where(['id' => $id])->first();
        if (!empty($res)) {
            OrderModel::where(['id' => $id])->delete();
            return response()->json(['status' => 200, 'msg' => '删除成功']);
        }
        return response()->json(['status' => 500, 'msg' => '删除失败']);
    }

    public function payok()
    {
        error_reporting(0);
        define('IN_MOBILE', true);
        libxml_disable_entity_loader(true);
        $xml = '<?xml version="1.0" encoding="utf-8"?>';
        $xml .= $GLOBALS['HTTP_RAW_POST_DATA'];
        $obj = simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA);
        $arrayinfo = xmlToArray($obj);
        if (($arrayinfo['result_code'] = 'SUCCESS' || $arrayinfo['return_code'] = 'SUCCESS')) {
            $out_trade_no = $arrayinfo['out_trade_no']; //商户订单号
            $transaction_id = $arrayinfo['transaction_id']; //微信订单支付订单号

            $result = OrderModel::where('out_trade_no', $out_trade_no)->find();
            if ($result['status'] != 1) {
                $data = array(
                    'status' => 1,
                    'transaction_id' => $transaction_id
                );
                $res = OrderModel::where('out_trade_no', $out_trade_no)->update($data);

                $user_info = OrderModel::where('out_trade_no', $out_trade_no)->first()->toArray();

                $result_tree = OrderModel::where('openid', $user_info['openid'])->orderBy('create_time', 'desc')->first();
                $result_tree_old = OrderModel::where('openid', $user_info['openid'])->where('out_trade_no', '!=', $out_trade_no)->orderBy('create_time', 'desc')->first();

                if (empty($result_tree_old) || date('Y-m-d', $result_tree_old->create_time) != date('Y-m-d', $result_tree->create_time)) {

                    DB::table('user')->where('openid', $user_info['openid'])->increment('tree_day');
                }
                if ($res) {
                    return '<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>';
                } else {
                    return '<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[NO]]></return_msg></xml>';
                }
            } else {
                return '<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>';
            }

        } else {
            return '<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[NO]]></return_msg></xml>';
        }

    }

    public function test()
    {

        $out_trade_no = 'e5c5f4ff0638d8f2a96d9a533f0c5107';
        $user_info = OrderModel::where('out_trade_no', $out_trade_no)->first();

        $result_tree = OrderModel::where('openid', $user_info['openid'])->orderBy('create_time', 'desc')->take(2);

        $one_time = null;
        foreach ($result_tree as $key => $value) {
            $one_time = $result_tree[1]['create_time'];
            dd($one_time);
        }
        var_dump(isset($result_tree->create_time));
        var_dump(empty($result_tree) || date('Y-m-d', time()) != date('Y-m-d', $result_tree->create_time));
        if (empty($result_tree) || date('Y-m-d', time()) != date('Y-m-d', $result_tree->create_time)) {

            DB::table('user')->where('openid', $user_info['openid'])->increment('tree_day');
        }
    }

    public function expressorder(Request $request)
    {
        if ($request->isMethod('get')) {
            $data['data'] = ExpressorderModel::paginate(10);
            $express = ExpressModel::get();
            $data['type'] = 3;
            return view('order.expressorder', compact('data', 'express'));

        } else {
            $where = [
                'role' => $request->input('role'),
                'express_id' => $request->input('express_id'),
                'datemax' => $request->input('datemax'),
                'datemin' => $request->input('datemin')
            ];
            $where = $this->where_data($where);
            if (!empty( $where['express_id'])){
              $express=ExpressModel::find($where['express_id']);
                $where['express']=$express->name;
                unset($where['express_id']);
            }

            if (!empty($where)) {
                if (isset($where['datemax'])) {
                    $datemax = $where['datemax'];
                    unset($where['datemax']);
                }
                if (isset($where['datemin'])) {
                    $datemin = $where['datemin'];
                    unset($where['datemin']);
                }


                if (!empty($datemax) && !empty($datemin)) {
                    /*                    echo $datemax ;
                                        echo date('Y-m-d H:i:s',$datemax) ;
                                        echo '<hr>';
                                        echo $datemin ;
                                        echo date('Y-m-d H:i:s',$datemin) ;*/
                    $data['data'] = ExpressorderModel::whereBetween('create_time', array($datemin, $datemax))
                        ->where($where)
                        ->paginate(10);
                    //dd( $data['data']);
                } elseif (!empty($datemin)) {

                    $data['data'] = ExpressorderModel::where('create_time', '>', $datemin)
                        ->where($where)
                        ->paginate(10);
                } elseif (!empty($datemax)) {
                    $data['data'] = ExpressorderModel::where('create_time', '<', $datemax)
                        ->where($where)
                        ->paginate(10);
                } else {
                    $data['data'] = ExpressorderModel::where($where)
                        ->paginate(10);
                }
            } else {
                $data['data'] = ExpressorderModel::paginate(10);
            }

            if ($request->input('status') == 1) {
                if (!empty($data['data'])) {
                    $data = $data['data']->toArray();
                    //dd( $data);
                    $this->save_express_excel($data['data']);
                }
            }
            $express = ExpressModel::get();
            $data['type'] = 3;
            return view('order.expressorder', compact('data', 'express'));
        }

    }

    public function expressorder_del(Request $request)
    {
        $id = $request->input('id');
        $res = ExpressorderModel::where(['id' => $id])->first();
        if (!empty($res)) {
            ExpressorderModel::where(['id' => $id])->delete();
            return response()->json(['status' => 200, 'msg' => '删除成功']);
        }
        return response()->json(['status' => 500, 'msg' => '删除失败']);
    }



    public function save_express_excel($data){

        foreach ($data as $k => $v) {
            if ($v['role'] == 1) {
                $data[$k]['role'] = '教师';
            } else {
                $data[$k]['role'] = '学生';
            }
            if ($v['status'] != 0) {
                $data[$k]['status'] = '已支付';
            } else {
                $data[$k]['status'] = '未支付';
            }
            $data[$k]['create_time'] = date('Y-m-d H:i:s', $v['create_time']);
        }

        header("Content-Type:text/html;charset=utf-8");
        error_reporting(E_ALL);
        ini_set('display_errors', TRUE);
        ini_set('display_startup_errors', TRUE);
        //创建对象
        $excel = new PHPExcel();
        $excel->getActiveSheet()->setTitle('寄件下单订单取送件');
        //Excel表格式,这里简略写了8列
        $letter = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S');
        //表头数组
        $tableheader = array('订单id', '快递公司','运单号', '寄件人','寄件地址', '寄件手机号', '寄件人身份证', '收件人', '收件人手机号', '备注物品', '收件人地址', '状态', '用户唯一标识', '价格', '订单编号', '创建时间', '角色');
        //填充表头信息
        for ($i = 0; $i < count($tableheader); $i++) {

            $excel->getActiveSheet()->setCellValue("$letter[$i]1", "$tableheader[$i]");
        }


        $data = json_decode(json_encode($data), true);

        //填充表格信息
        for ($i = 2; $i <= count($data) + 1; $i++) {
            $j = 0;
            foreach ($data[$i - 2] as $key => $value) {
                $excel->getActiveSheet()->setCellValue("$letter[$j]$i", "$value");
                $j++;
            }
        }

        //创建Excel输入对象
        ob_end_clean();
        $objWriter = new \PHPExcel_Writer_Excel5($excel);
        header("Pragma: public");
        header("Expires: 0");
        header("Cache-Control:must-revalidate, post-check=0, pre-check=0");
        header("Content-Type:application/force-download");
        header("Content-Type:application/vnd.ms-execl");
        header("Content-Type:application/octet-stream");
        header("Content-Type:application/download");
        //多浏览器下兼容中文标题
        $fileName = '寄件下单订单取送件' . date("Y-m-d-h-i-s", time());
        $encoded_filename = urlencode($fileName);
        $ua = $_SERVER["HTTP_USER_AGENT"];
        if (preg_match("/MSIE/", $ua)) {
            header('Content-Disposition: attachment; filename="' . $encoded_filename . '.xls"');
        } else if (preg_match("/Firefox/", $ua)) {
            header('Content-Disposition: attachment; filename*="utf8\'\'' . $fileName . '.xls"');
        } else {
            header('Content-Disposition: attachment; filename="' . $fileName . '.xls"');
        }
        header("Content-Transfer-Encoding:binary");
        $objWriter->save('php://output');


    }

}
